package com.kele.demo.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kele.demo.dto.RegisterDTO;
import com.kele.demo.entity.LoginUser;
import com.kele.demo.mapper.LoginUserMapper;
import com.kele.demo.service.LoginUserService;
import com.kele.framework.exception.utils.BadRequestException;
import com.kele.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.stream.Stream;

/**
 * @author chunhui.li
 * @date 2022/2/15 16:02
 * @Description
 * @ClassName LoginUserServiceImpl
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements LoginUserService {


    @Autowired
    RedisUtil redisUtil;

    public static final String TOKEN_REDIS_KEY = "Authorization:token:";
    public static final String TOKEN_KEY = "Authorization";

    /**
     * 登陆
     */
    @Override
    public LoginUser getUser(LoginUser loginUser) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", loginUser.getUserName());
        queryWrapper.eq("password", SecureUtil.md5(loginUser.getPassword()));
        LoginUser userInfo = this.baseMapper.selectOne(queryWrapper);
        if (userInfo != null) {

            /**
             * 查询有用户,创建token
             */
            return createToken(userInfo);


            /**
             * 看是不是重复登陆且token还没有过期那么就更新这个key
             */
//            String key = userInfo.getUserName()+"_"+userInfo.getId();
//            LoginUser userInfoWithToken = (LoginUser) redisUtil.get(key);
//            if(userInfoWithToken!=null){
//                System.out.println("==============>>>> 用户已经登陆过 ");
//                redisUtil.del(key);
//                return createToken(userInfo);
//            }else {
//                System.out.println("==============>>>> 用户没有登陆过,创建token ");
//                return createToken(userInfo);
//            }
        }
        return null;
    }

    /*注册*/
    @Override
    public int registerUser(RegisterDTO registerDTO) {
        LoginUser user = new LoginUser();
        if (registerDTO != null) {
            user.setUserName(registerDTO.getUserName());
            /**
             * 加密
             */
            String encPwd = SecureUtil.md5(registerDTO.getPassword());
            user.setPassword(encPwd);
            user.setEmail(registerDTO.getEmail());
            user.setPhone(registerDTO.getPhone());
            user.setIsSuper(0);
            return this.baseMapper.insert(user);
        }
        return 0;
    }

    /**
     * 创建token
     *
     * @param loginUser 登陆的用户信息
     * @return 返回创建的token放在登陆的用户信息中
     */
    public LoginUser createToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString();
        loginUser.setToken(token);
        long expireTime = 60 * 5;
        /**
         * 以token为key,value存放用户的信息
         */
        boolean result = redisUtil.set(TOKEN_REDIS_KEY + token, loginUser, expireTime);
        if (result) {
            return loginUser;
        } else {
            throw new BadRequestException("登陆失败");
        }
    }

    /**
     * 校验token
     *
     * @param token 登陆的token令牌
     * @return 返回校验是否通过
     */
    public Boolean checkToken(String token) {
        if (StringUtils.isNotBlank(token)) {
            LoginUser userInfoOnRedis = (LoginUser) redisUtil.get(TOKEN_REDIS_KEY + token);
            if (userInfoOnRedis != null && userInfoOnRedis.getToken().equals(token)) {
                return true;
            }
        }
        return false;
    }
}
